package com.example.rice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rice.dto.DishDto;
import com.example.rice.entity.Dish;
import com.example.rice.entity.DishFlavor;
import com.example.rice.mapper.DishMapper;
import com.example.rice.service.DishFlavorService;
import com.example.rice.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * 新增菜品同时保存对应的口味数据
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //基本信息保存到dish中
        this.save(dishDto);

        //获取dishid
        Long dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) ->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味到口味表
        dishFlavorService.saveBatch(flavors);

    }


    /**
     * 根据id查询菜品信息与口味信息
     * @param id
     * @return
     */
    @Transactional
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息,直接调用继承的IService里的方法
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //拷贝dish基本信息
        BeanUtils.copyProperties(dish,dishDto);
        //条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 修改方法实现
     * @param dishDto
     */
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //首先更新dish表
        this.updateById(dishDto);
        //清理菜品口味
        LambdaQueryWrapper<DishFlavor>  queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //插入菜品口味
        List<DishFlavor>  flavors = dishDto.getFlavors();
        //通过循环把所有需要添加的口味插入一个id
        flavors = flavors.stream().map((item) ->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
